package bean.converter;

import javax.ejb.EJB;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.ConverterException;

import eao.EaoState;
import entity.State;

@ManagedBean
@RequestScoped
public class StateConverter implements Converter {

    @EJB private EaoState eaoState;

    @Override
    public String getAsString(FacesContext context, UIComponent component, Object value) {
        if (!(value instanceof State) || ((State) value).getId() == null) {
        	return null;
        }

        return String.valueOf(((State) value).getId());
    }

    @Override
    public Object getAsObject(FacesContext context, UIComponent component, String value) {
        if (value == null || !value.matches("\\d+")) {
        	return null;
        }

        State state = eaoState.find(Integer.valueOf(value));

        if (state == null) {
        	throw new ConverterException(new FacesMessage("Unknown operation ID: " + value));
        }

        return state;
    }

}